<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Vuex 状态管理 | Justic</title><meta name="keywords" content="Vue"><meta name="author" content="Justic"><meta name="copyright" content="Justic"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Vuex 状态管理1、主要内容 Vuex核心概念和基本使用回顾 购物车案例 模拟实现Vuex  2、组件内状态管理流程下面我们通过组件内状态管理的流程来回顾一下什么是组件内状态管理。VUE中最核心的两个功能就是数据驱动与组件化，使用组件化的开发，可以提高开发效率，提高可维护性。 new Vue(&amp;#123;  data() &amp;#123;    return &amp;#123;      count: 0">
<meta property="og:type" content="article">
<meta property="og:title" content="Vuex 状态管理">
<meta property="og:url" content="http://example.com/2022/07/15/Vue/Vuex%20%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86/Vuex%20%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86/index.html">
<meta property="og:site_name" content="Justic">
<meta property="og:description" content="Vuex 状态管理1、主要内容 Vuex核心概念和基本使用回顾 购物车案例 模拟实现Vuex  2、组件内状态管理流程下面我们通过组件内状态管理的流程来回顾一下什么是组件内状态管理。VUE中最核心的两个功能就是数据驱动与组件化，使用组件化的开发，可以提高开发效率，提高可维护性。 new Vue(&amp;#123;  data() &amp;#123;    return &amp;#123;      count: 0">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/m9/wallhaven-m9y289.png">
<meta property="article:published_time" content="2022-07-15T12:05:37.000Z">
<meta property="article:modified_time" content="2022-07-21T08:35:49.853Z">
<meta property="article:author" content="Justic">
<meta property="article:tag" content="Vue">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/m9/wallhaven-m9y289.png"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="http://example.com/2022/07/15/Vue/Vuex%20%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86/Vuex%20%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Vuex 状态管理',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-07-21 16:35:49'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><!-- hexo injector head_end start --><link rel="stylesheet" href="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/clock.min.css" /><!-- hexo injector head_end end --><meta name="generator" content="Hexo 6.2.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://portrait.gitee.com/uploads/avatars/user/2982/8948190_JIAXInT_1624177607.png!avatar200" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">22</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">2</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">3</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 博文</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/project/"><i class="fa-fw fas fa-images"></i><span> 项目</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于笔者</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/m9/wallhaven-m9y289.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Justic</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 博文</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/project/"><i class="fa-fw fas fa-images"></i><span> 项目</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于笔者</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Vuex 状态管理</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-07-15T12:05:37.000Z" title="发表于 2022-07-15 20:05:37">2022-07-15</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-07-21T08:35:49.853Z" title="更新于 2022-07-21 16:35:49">2022-07-21</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Vue/">Vue</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">4.7k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>19分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Vuex 状态管理"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span><span class="post-meta-separator">|</span><span class="post-meta-commentcount"><i class="far fa-comments fa-fw post-meta-icon"></i><span class="post-meta-label">评论数:</span><a href="/2022/07/15/Vue/Vuex%20%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86/Vuex%20%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86/#post-comment" itemprop="discussionUrl"><span class="valine-comment-count" data-xid="/2022/07/15/Vue/Vuex%20%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86/Vuex%20%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86/" itemprop="commentCount"><i class="fa-solid fa-spinner fa-spin"></i></span></a></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="Vuex-状态管理"><a href="#Vuex-状态管理" class="headerlink" title="Vuex 状态管理"></a>Vuex 状态管理</h1><h1 id="1、主要内容"><a href="#1、主要内容" class="headerlink" title="1、主要内容"></a>1、主要内容</h1><ul>
<li><code>Vuex</code>核心概念和基本使用回顾</li>
<li>购物车案例</li>
<li>模拟实现<code>Vuex</code></li>
</ul>
<h1 id="2、组件内状态管理流程"><a href="#2、组件内状态管理流程" class="headerlink" title="2、组件内状态管理流程"></a>2、组件内状态管理流程</h1><p>下面我们通过组件内状态管理的流程来回顾一下什么是组件内状态管理。<code>VUE</code>中最核心的两个功能就是数据驱动与组件化，使用组件化的开发，可以提高开发效率，提高可维护性。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="title class_">Vue</span>(&#123;</span><br><span class="line">  <span class="title function_">data</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">      <span class="attr">count</span>: <span class="number">0</span>,</span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">template</span>: <span class="string">`&lt;div&gt;&#123;&#123;count&#125;&#125;&lt;/div&gt;`</span>,</span><br><span class="line">  <span class="attr">methods</span>: &#123;</span><br><span class="line">    <span class="title function_">add</span>(<span class="params"></span>) &#123;</span><br><span class="line">      <span class="variable language_">this</span>.<span class="property">count</span>++;</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>每个组件内都有自己的数据，模板，和方法。数据也称之为状态，每个组件都维护自己的状态。模板我们可以称之为视图，每个组件都有自己的视图，把状态绑定到视图上，最终呈现给用户。当用户与视图交换的时候，可能会更改状态，例如单击按钮，让<code>count</code>的值发生变化，当状态发生变化后，会自动更新到视图，更改状态的部分，我们可以称之为<code>actions</code>(方法)，以上描述的是单个组件的状态管理。但是在实际的开发中，可能多个组件都会共享状态，我们所说的状态管理，其实就是对状态集中管理和分发，解决多个组件共享状态的问题。</p>
<p>下面我们来看一下状态管理的组成：</p>
<ul>
<li><code>state</code>:驱动应用的数据源（也就是状态）</li>
<li><code>view</code>:以声明方式将<code>state</code>映射到视图（通过把状态绑定到视图呈现给用户）</li>
<li><code>actions</code>:响应在<code>view</code>上的用户输入导致的状态变化。（用户与视图交换，改变状态的方式）</li>
</ul>
<h1 id="3、简易的状态管理方案"><a href="#3、简易的状态管理方案" class="headerlink" title="3、简易的状态管理方案"></a>3、简易的状态管理方案</h1><p>在前面的课程中，我们讲解过多种的状态管理方案，例如，父组件向子组件传递数据，子组件向父组件传递数据，以及兄弟组件之间的数据传递等。但是当多个视图依赖同一状态，或者来自不同视图的行为需要变更同一状态的时候，以上的方案就变得非常的麻烦，而且让代码变得不可维护。</p>
<p>为了解决这些问题，我们可以将不同组件共享的状态抽取出来，存储到一个全局的对象中，并且保证在将来使用该对象的时候，它是响应式的。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">  <span class="attr">state</span>: &#123;</span><br><span class="line">    <span class="attr">user</span>: &#123;</span><br><span class="line">      <span class="attr">name</span>: <span class="string">&quot;zhangsan&quot;</span>,</span><br><span class="line">      <span class="attr">age</span>: <span class="number">18</span>,</span><br><span class="line">      <span class="attr">sex</span>: <span class="string">&quot;男&quot;</span>,</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="title function_">setUserNameAction</span>(<span class="params">name</span>) &#123;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">user</span>.<span class="property">name</span> = name;</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p><code>componentA.vue</code>文件中的代码如下：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&lt;template&gt;</span><br><span class="line">  &lt;div&gt;</span><br><span class="line">    &lt;h1&gt;componentA&lt;/h1&gt;</span><br><span class="line">    userName:&#123;&#123; sharedState.user.name &#125;&#125;</span><br><span class="line">    &lt;button @click=&quot;change&quot;&gt;修改&lt;/button&gt;</span><br><span class="line">  &lt;/div&gt;</span><br><span class="line">&lt;/template&gt;</span><br><span class="line">&lt;script&gt;</span><br><span class="line">import store from &quot;./store&quot;;</span><br><span class="line">export default &#123;</span><br><span class="line">  methods: &#123;</span><br><span class="line">    change() &#123;</span><br><span class="line">      store.setUserNameAction(&quot;componentA&quot;);</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;,</span><br><span class="line">  data() &#123;</span><br><span class="line">    return &#123;</span><br><span class="line">      sharedState: store.state,</span><br><span class="line">      privateState: &#123;&#125;, //可以存储私有的状态</span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;;</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>

<p><code>componentB.vue</code>文件中的内容如下：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&lt;template&gt;</span><br><span class="line">  &lt;div&gt;</span><br><span class="line">    &lt;h1&gt;componentB&lt;/h1&gt;</span><br><span class="line">    userName:&#123;&#123; sharedState.user.name &#125;&#125;</span><br><span class="line">    &lt;button @click=&quot;change&quot;&gt;修改&lt;/button&gt;</span><br><span class="line">  &lt;/div&gt;</span><br><span class="line">&lt;/template&gt;</span><br><span class="line">&lt;script&gt;</span><br><span class="line">import store from &quot;./store&quot;;</span><br><span class="line">export default &#123;</span><br><span class="line">  methods: &#123;</span><br><span class="line">    change() &#123;</span><br><span class="line">      store.setUserNameAction(&quot;componentB&quot;);</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;,</span><br><span class="line">  data() &#123;</span><br><span class="line">    return &#123;</span><br><span class="line">      sharedState: store.state,</span><br><span class="line">      privateState: &#123;&#125;, //可以存储私有的状态</span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;;</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>

<p>以上两个组件文件内的代码是一样的，只是修改了不用的名称。</p>
<p><code>App.vue</code>文件中的代码修改如下：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&lt;template&gt;</span><br><span class="line">  &lt;div id=&quot;app&quot;&gt;</span><br><span class="line">    &lt;ComponentA&gt;&lt;/ComponentA&gt;</span><br><span class="line">    &lt;ComponentB&gt;&lt;/ComponentB&gt;</span><br><span class="line">  &lt;/div&gt;</span><br><span class="line">&lt;/template&gt;</span><br><span class="line"></span><br><span class="line">&lt;script&gt;</span><br><span class="line">import ComponentA from &quot;./components/simplestate/componentA&quot;;</span><br><span class="line">import ComponentB from &quot;./components/simplestate/componentB&quot;;</span><br><span class="line"></span><br><span class="line">export default &#123;</span><br><span class="line">  name: &quot;App&quot;,</span><br><span class="line">  components: &#123;</span><br><span class="line">    ComponentA,</span><br><span class="line">    ComponentB,</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;;</span><br><span class="line">&lt;/script&gt;</span><br><span class="line"></span><br><span class="line">&lt;style&gt;</span><br><span class="line">#app &#123;</span><br><span class="line">  font-family: Avenir, Helvetica, Arial, sans-serif;</span><br><span class="line">  -webkit-font-smoothing: antialiased;</span><br><span class="line">  -moz-osx-font-smoothing: grayscale;</span><br><span class="line">  text-align: center;</span><br><span class="line">  color: #2c3e50;</span><br><span class="line">  margin-top: 60px;</span><br><span class="line">&#125;</span><br><span class="line">&lt;/style&gt;</span><br></pre></td></tr></table></figure>

<p>在浏览器中进行测试的时候，单击不同组件中的按钮，都可以完成对公共状态的更新，这样就实现了对公共状态的一个全局管理的功能，当然在更新状态的时候，我们约定，不能直接修改对应的状态，而是通过相应的方法来实现对状态数据的更新操作。</p>
<p>以上就是我们所讲解的简易的状态管理方案，下一小节开始介绍<code>vuex</code>.</p>
<h1 id="4、什么是-Vuex"><a href="#4、什么是-Vuex" class="headerlink" title="4、什么是 Vuex"></a>4、什么是 Vuex</h1><p><code>Vuex</code>是专门为<code>Vue.js</code>设计的状态管理库。</p>
<p><code>Vuex</code>采用集中式的方式存储需要共享的状态。</p>
<p><code>Vuex</code>的作用是进行状态管理，解决复杂组件通信，数据共享的问题。</p>
<p>什么情况下使用<code>Vuex</code>?</p>
<p>非必要的情况下不要使用<code>Vuex</code>.</p>
<p>如果是小项目，并且不会涉及到大量组件的通信，不需要使用<code>Vuex</code>,使用反而增加了项目的复杂度。</p>
<p>如果是开发大型的单页应用程序，这时会涉及到多个视图依赖于同一状态，并且来自不同视图的行为需要变更同一状态，这时就需要用到<code>Vuex</code>.</p>
<p>例如：我们后面所要实现的购物车案例。</p>
<h1 id="5、Vuex-核心概念"><a href="#5、Vuex-核心概念" class="headerlink" title="5、Vuex 核心概念"></a>5、Vuex 核心概念</h1><p>下面我们通过一张图来理解一下<code>Vuex</code>中的核心概念。</p>
<p>![](Vuex 状态管理&#x2F;Vuex.png)</p>
<h1 id="6、Vuex-基本结构"><a href="#6、Vuex-基本结构" class="headerlink" title="6、Vuex 基本结构"></a>6、Vuex 基本结构</h1><p>基本结构如下：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="title class_">Vue</span> <span class="keyword">from</span> <span class="string">`vue`</span></span><br><span class="line"><span class="keyword">import</span> <span class="title class_">Vuex</span> <span class="keyword">from</span> <span class="string">`vuex`</span></span><br><span class="line"><span class="title class_">Vue</span>.<span class="title function_">use</span>(<span class="title class_">Vuex</span>) <span class="comment">//Vuex是Vue的插件</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="keyword">new</span> <span class="title class_">Vuex</span>.<span class="title class_">Store</span>(&#123;</span><br><span class="line">    <span class="attr">state</span>:&#123;&#125;,</span><br><span class="line">    <span class="attr">mutations</span>:&#123;&#125;,</span><br><span class="line">    <span class="attr">actions</span>:&#123;&#125;,</span><br><span class="line">    <span class="attr">modules</span>:&#123;&#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>下面把<code>Store</code>注入到<code>Vue</code>的实例中。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> store <span class="keyword">from</span> <span class="string">&quot;./store&quot;</span>;</span><br><span class="line"><span class="keyword">new</span> <span class="title class_">Vue</span>(&#123;</span><br><span class="line">  router,</span><br><span class="line">  store,</span><br><span class="line">  <span class="attr">render</span>: <span class="function">(<span class="params">h</span>) =&gt;</span> <span class="title function_">h</span>(<span class="title class_">App</span>),</span><br><span class="line">&#125;).$mount(<span class="string">&quot;#app&quot;</span>);</span><br></pre></td></tr></table></figure>

<h1 id="7、State"><a href="#7、State" class="headerlink" title="7、State"></a>7、State</h1><p>这一小节，我们来学习一下<code>State</code>的应用，在<code>State</code>中存储了状态数据，并且<code>State</code>是响应式的，如果要获取数据直接从<code>State</code>中获取。</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">npm install vuex --save</span><br></pre></td></tr></table></figure>

<p>在项目的<code>src</code>目录下面创建<code>store</code>目录，在该目录中创建<code>index.js</code>文件，该文件中的代码如下：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="title class_">Vue</span> <span class="keyword">from</span> <span class="string">&quot;vue&quot;</span>;</span><br><span class="line"><span class="keyword">import</span> <span class="title class_">Vuex</span> <span class="keyword">from</span> <span class="string">&quot;vuex&quot;</span>;</span><br><span class="line"><span class="title class_">Vue</span>.<span class="title function_">use</span>(<span class="title class_">Vuex</span>);</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="keyword">new</span> <span class="title class_">Vuex</span>.<span class="title class_">Store</span>(&#123;</span><br><span class="line">  <span class="attr">state</span>: &#123;</span><br><span class="line">    <span class="attr">count</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">msg</span>: <span class="string">&quot;Hello Vuex&quot;</span>,</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">mutations</span>: &#123;&#125;,</span><br><span class="line">  <span class="attr">actions</span>: &#123;&#125;,</span><br><span class="line">  <span class="attr">modules</span>: &#123;&#125;,</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>在<code>state</code>中定义了两个状态属性。</p>
<p>下面要在<code>main.js</code>文件中将<code>store</code>注册到<code>Vue</code>的实例中。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="title class_">Vue</span> <span class="keyword">from</span> <span class="string">&quot;vue&quot;</span>;</span><br><span class="line"><span class="keyword">import</span> <span class="title class_">App</span> <span class="keyword">from</span> <span class="string">&quot;./App.vue&quot;</span>;</span><br><span class="line"><span class="keyword">import</span> store <span class="keyword">from</span> <span class="string">&quot;./store&quot;</span>;</span><br><span class="line"><span class="title class_">Vue</span>.<span class="property">config</span>.<span class="property">productionTip</span> = <span class="literal">false</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">new</span> <span class="title class_">Vue</span>(&#123;</span><br><span class="line">  store,</span><br><span class="line">  <span class="attr">render</span>: <span class="function">(<span class="params">h</span>) =&gt;</span> <span class="title function_">h</span>(<span class="title class_">App</span>),</span><br><span class="line">&#125;).$mount(<span class="string">&quot;#app&quot;</span>);</span><br></pre></td></tr></table></figure>

<p>这样我们在任何的<code>Vue</code>组件中都可以通过<code>$store</code>的形式来获取<code>state</code>中的状态数据，然后展示在页面中。</p>
<p>下面，在<code>App.vue</code>这个组件中，展示一下对应的<code>state</code>中的状态数据。</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&lt;template&gt;</span><br><span class="line">  &lt;div id=&quot;app&quot;&gt;</span><br><span class="line">    &lt;ComponentA&gt;&lt;/ComponentA&gt;</span><br><span class="line">    &lt;ComponentB&gt;&lt;/ComponentB&gt;</span><br><span class="line">    &lt;hr /&gt;</span><br><span class="line">    &lt;h1&gt;Vuex-Demo&lt;/h1&gt;</span><br><span class="line">    count:&#123;&#123; $store.state.count &#125;&#125; &lt;br /&gt;</span><br><span class="line">    msg:&#123;&#123; $store.state.msg &#125;&#125;</span><br><span class="line">  &lt;/div&gt;</span><br><span class="line">&lt;/template&gt;</span><br></pre></td></tr></table></figure>

<p>在上面的代码中，展示了对应的<code>state</code>中的<code>count</code>与<code>msg</code>中的数据。</p>
<p>但是问题是，这种写法比较复杂一些，下面我们简化一下这个过程。</p>
<p>这里需要借助与<code>mapState</code>函数以及计算属性来完成。</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&lt;template&gt;</span><br><span class="line">  &lt;div id=&quot;app&quot;&gt;</span><br><span class="line">    &lt;!-- &lt;ComponentA&gt;&lt;/ComponentA&gt;</span><br><span class="line">    &lt;ComponentB&gt;&lt;/ComponentB&gt; --&gt;</span><br><span class="line">    &lt;hr /&gt;</span><br><span class="line">    &lt;h1&gt;Vuex-Demo&lt;/h1&gt;</span><br><span class="line">    &lt;!-- count:&#123;&#123; $store.state.count &#125;&#125; &lt;br /&gt;</span><br><span class="line">    msg:&#123;&#123; $store.state.msg &#125;&#125;</span><br><span class="line">   --&gt;</span><br><span class="line">    &lt;!--直接简化成如下的形式---&gt;</span><br><span class="line">    count:&#123;&#123; count &#125;&#125;&lt;br /&gt;</span><br><span class="line">    msg:&#123;&#123; msg &#125;&#125;</span><br><span class="line">  &lt;/div&gt;</span><br><span class="line">&lt;/template&gt;</span><br></pre></td></tr></table></figure>

<h1 id="8、Getter"><a href="#8、Getter" class="headerlink" title="8、Getter"></a>8、Getter</h1><p><code>Getter</code>类似于组件中的计算属性，如果需要对<code>State</code>的中的数据做一些简单的处理，可以使用<code>Getter</code>,例如把<code>msg</code>中的数据倒序输出，或者过滤商品数据等。</p>
<p>下面我们来看一下关于<code>Getter</code>的基本使用，这里我们把前面指定的<code>msg</code>状态中的内容倒序输出，以前我们都是在组件中通过计算属性的形式来完成这种操作。</p>
<p>在<code>Vuex</code>中，我们需要通过<code>Getter</code>来完成。因为<code>msg</code>这个状态是属于<code>Vuex</code>,所以关于它的处理需要在<code>Vuex</code>中完成。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="title class_">Vue</span> <span class="keyword">from</span> <span class="string">&quot;vue&quot;</span>;</span><br><span class="line"><span class="keyword">import</span> <span class="title class_">Vuex</span> <span class="keyword">from</span> <span class="string">&quot;vuex&quot;</span>;</span><br><span class="line"><span class="title class_">Vue</span>.<span class="title function_">use</span>(<span class="title class_">Vuex</span>);</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="keyword">new</span> <span class="title class_">Vuex</span>.<span class="title class_">Store</span>(&#123;</span><br><span class="line">  <span class="attr">state</span>: &#123;</span><br><span class="line">    <span class="attr">count</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">msg</span>: <span class="string">&quot;Hello Vuex&quot;</span>,</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="attr">getters</span>: &#123;</span><br><span class="line">    <span class="title function_">reverseMsg</span>(<span class="params">state</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> state.<span class="property">msg</span>.<span class="title function_">split</span>(<span class="string">&quot;&quot;</span>).<span class="title function_">reverse</span>().<span class="title function_">join</span>(<span class="string">&quot;&quot;</span>);</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">mutations</span>: &#123;&#125;,</span><br><span class="line">  <span class="attr">actions</span>: &#123;&#125;,</span><br><span class="line">  <span class="attr">modules</span>: &#123;&#125;,</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>下面返回到<code>App.vue</code>文件中的模板，使用<code>getters</code>.模板的代码如下：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&lt;template&gt;</span><br><span class="line">  &lt;div id=&quot;app&quot;&gt;</span><br><span class="line">    &lt;!-- &lt;ComponentA&gt;&lt;/ComponentA&gt;</span><br><span class="line">    &lt;ComponentB&gt;&lt;/ComponentB&gt; --&gt;</span><br><span class="line">    &lt;hr /&gt;</span><br><span class="line">    &lt;h1&gt;Vuex-Demo&lt;/h1&gt;</span><br><span class="line">    &lt;!-- count:&#123;&#123; $store.state.count &#125;&#125; &lt;br /&gt;</span><br><span class="line">    msg:&#123;&#123; $store.state.msg &#125;&#125;</span><br><span class="line">   --&gt;</span><br><span class="line">    &lt;!-- count:&#123;&#123; count &#125;&#125;&lt;br /&gt;</span><br><span class="line">    msg:&#123;&#123; msg &#125;&#125; --&gt;</span><br><span class="line">    count:&#123;&#123; num &#125;&#125;&lt;br /&gt;</span><br><span class="line">    msg:&#123;&#123; message &#125;&#125;</span><br><span class="line"></span><br><span class="line">    &lt;!--下面使用Getters---&gt;</span><br><span class="line">    &lt;h2&gt;Getters&lt;/h2&gt;</span><br><span class="line">    reverseMsg:&#123;&#123; $store.getters.reverseMsg &#125;&#125;</span><br><span class="line">  &lt;/div&gt;</span><br><span class="line">&lt;/template&gt;</span><br></pre></td></tr></table></figure>

<p>修改后的代码如下所示：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; mapGetters, mapState &#125; <span class="keyword">from</span> <span class="string">&quot;vuex&quot;</span>;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">  <span class="attr">computed</span>: &#123;</span><br><span class="line">    <span class="comment">//mapState会返回一个对象，包含了两个计算属性对应的方法，</span></span><br><span class="line">    <span class="comment">//当前的计算属性为count和msg</span></span><br><span class="line">    <span class="comment">//所以对应的方法形式为: count:state=&gt;state.count</span></span><br><span class="line">    <span class="comment">// ...mapState([&quot;count&quot;, &quot;msg&quot;]),</span></span><br><span class="line">    ...<span class="title function_">mapState</span>(&#123; <span class="attr">num</span>: <span class="string">&quot;count&quot;</span>, <span class="attr">message</span>: <span class="string">&quot;msg&quot;</span> &#125;),</span><br><span class="line">    ...<span class="title function_">mapGetters</span>([<span class="string">&quot;reverseMsg&quot;</span>]),</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>模板修改如下：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&lt;h2&gt;</span><br><span class="line">      Getters</span><br><span class="line">    &lt;/h2&gt;</span><br><span class="line">&lt;!-- reverseMsg:&#123;&#123; $store.getters.reverseMsg &#125;&#125; --&gt;</span><br><span class="line">reverseMsg:&#123;&#123; reverseMsg &#125;&#125;</span><br></pre></td></tr></table></figure>

<p>以上就是<code>Getters</code>的基本使用。当我们需要对视图中的数据做一些简单的处理，然后进行展示，就可以使用<code>Getters</code>.</p>
<h1 id="9、Mutation"><a href="#9、Mutation" class="headerlink" title="9、Mutation"></a>9、Mutation</h1><p>在前面的演示中，我们都是展示<code>Store</code>中的状态数据，那应该怎样对状态数据进行修改呢？这就需要用到<code>Mutaion</code>.</p>
<p>状态数据的修改必须提交<code>Mutaion</code>,并且<code>Mutaion</code>的修改必须是同步执行的。</p>
<p>下面，我们要实现的案例，就是单击视图中的按钮，完成<code>count</code>这个状态值的累加。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="title class_">Vue</span> <span class="keyword">from</span> <span class="string">&quot;vue&quot;</span>;</span><br><span class="line"><span class="keyword">import</span> <span class="title class_">Vuex</span> <span class="keyword">from</span> <span class="string">&quot;vuex&quot;</span>;</span><br><span class="line"><span class="title class_">Vue</span>.<span class="title function_">use</span>(<span class="title class_">Vuex</span>);</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="keyword">new</span> <span class="title class_">Vuex</span>.<span class="title class_">Store</span>(&#123;</span><br><span class="line">  <span class="attr">state</span>: &#123;</span><br><span class="line">    <span class="attr">count</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">msg</span>: <span class="string">&quot;Hello Vuex&quot;</span>,</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="attr">getters</span>: &#123;</span><br><span class="line">    <span class="title function_">reverseMsg</span>(<span class="params">state</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> state.<span class="property">msg</span>.<span class="title function_">split</span>(<span class="string">&quot;&quot;</span>).<span class="title function_">reverse</span>().<span class="title function_">join</span>(<span class="string">&quot;&quot;</span>);</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">mutations</span>: &#123;</span><br><span class="line">    <span class="comment">//payload是调用mutations的时候传递的额外的值。</span></span><br><span class="line">    <span class="comment">//这里就是传递过来的要累加的值</span></span><br><span class="line">    <span class="title function_">increate</span>(<span class="params">state, payload</span>) &#123;</span><br><span class="line">      state.<span class="property">count</span> += payload;</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">actions</span>: &#123;&#125;,</span><br><span class="line">  <span class="attr">modules</span>: &#123;&#125;,</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>下面修改模板中的代码。</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&lt;h2&gt;Mutation&lt;/h2&gt;</span><br><span class="line">&lt;button @click=&quot;$store.commit(&#x27;increate&#x27;, 2)&quot;&gt;计算&lt;/button&gt;</span><br></pre></td></tr></table></figure>

<p>。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; mapGetters, mapState, mapMutations &#125; <span class="keyword">from</span> <span class="string">&quot;vuex&quot;</span>;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">  <span class="attr">computed</span>: &#123;</span><br><span class="line">    <span class="comment">//mapState会返回一个对象，包含了两个计算属性对应的方法，</span></span><br><span class="line">    <span class="comment">//当前的计算属性为count和msg</span></span><br><span class="line">    <span class="comment">//所以对应的方法形式为: count:state=&gt;state.count</span></span><br><span class="line">    <span class="comment">// ...mapState([&quot;count&quot;, &quot;msg&quot;]),</span></span><br><span class="line">    ...<span class="title function_">mapState</span>(&#123; <span class="attr">num</span>: <span class="string">&quot;count&quot;</span>, <span class="attr">message</span>: <span class="string">&quot;msg&quot;</span> &#125;),</span><br><span class="line">    ...<span class="title function_">mapGetters</span>([<span class="string">&quot;reverseMsg&quot;</span>]),</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">methods</span>: &#123;</span><br><span class="line">    ...<span class="title function_">mapMutations</span>([<span class="string">&quot;increate&quot;</span>]),</span><br><span class="line">  &#125;,</span><br></pre></td></tr></table></figure>

<p>模板的修改如下：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&lt;h2&gt;Mutation&lt;/h2&gt;</span><br><span class="line">&lt;!-- &lt;button @click=&quot;$store.commit(&#x27;increate&#x27;, 2)&quot;&gt;计算&lt;/button&gt; --&gt;</span><br><span class="line">&lt;button @click=&quot;increate(3)&quot;&gt;计算&lt;/button&gt;</span><br></pre></td></tr></table></figure>

<h1 id="10、Action"><a href="#10、Action" class="headerlink" title="10、Action"></a>10、Action</h1><p>如果需要执行异步操作，我们需要通过<code>Action</code>来完成。</p>
<p>如果异步执行完毕后，需要修改状态，需要提交<code>Mutation</code>来修改<code>State</code>状态。因为所有的状态的修改都需要通过<code>Mutation</code>来完成。</p>
<p>例如：我们需要异步获取商品数据，就需要在<code>Action</code>中发送请求，异步完成后，需要提交<code>Mutation</code>,把数据记录到<code>State</code>中。</p>
<p>下面，我们来看一下<code>Action</code>的基本使用，我们这里通过<code>setTimeout</code>来模拟异步操作，延迟 2 秒钟，修改<code>count</code>的值。</p>
<p>下面在<code>Store</code>中创建<code>Action</code>.</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="title class_">Vue</span> <span class="keyword">from</span> <span class="string">&quot;vue&quot;</span>;</span><br><span class="line"><span class="keyword">import</span> <span class="title class_">Vuex</span> <span class="keyword">from</span> <span class="string">&quot;vuex&quot;</span>;</span><br><span class="line"><span class="title class_">Vue</span>.<span class="title function_">use</span>(<span class="title class_">Vuex</span>);</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="keyword">new</span> <span class="title class_">Vuex</span>.<span class="title class_">Store</span>(&#123;</span><br><span class="line">  <span class="attr">state</span>: &#123;</span><br><span class="line">    <span class="attr">count</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">msg</span>: <span class="string">&quot;Hello Vuex&quot;</span>,</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="attr">getters</span>: &#123;</span><br><span class="line">    <span class="title function_">reverseMsg</span>(<span class="params">state</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> state.<span class="property">msg</span>.<span class="title function_">split</span>(<span class="string">&quot;&quot;</span>).<span class="title function_">reverse</span>().<span class="title function_">join</span>(<span class="string">&quot;&quot;</span>);</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">mutations</span>: &#123;</span><br><span class="line">    <span class="comment">//payload是调用mutations的时候传递的额外的值。</span></span><br><span class="line">    <span class="comment">//这里就是传递过来的要累加的值</span></span><br><span class="line">    <span class="title function_">increate</span>(<span class="params">state, payload</span>) &#123;</span><br><span class="line">      state.<span class="property">count</span> += payload;</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">//创建Aciton</span></span><br><span class="line">  <span class="attr">actions</span>: &#123;</span><br><span class="line">    <span class="comment">//context:上下文，该对象中包含了state,commit,getters等成员</span></span><br><span class="line">    <span class="title function_">increateAsync</span>(<span class="params">context, payload</span>) &#123;</span><br><span class="line">      <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        context.<span class="title function_">commit</span>(<span class="string">&quot;increate&quot;</span>, payload);</span><br><span class="line">      &#125;, <span class="number">2000</span>);</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">modules</span>: &#123;&#125;,</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>下面修改<code>App.vue</code>中的模板。</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&lt;h2&gt;Action&lt;/h2&gt;</span><br><span class="line">&lt;button @click=&quot;$store.dispatch(&#x27;increateAsync&#x27;, 5)&quot;&gt;Action&lt;/button&gt;</span><br></pre></td></tr></table></figure>

<p>注意：这里对<code>Action</code>的执行需要通过<code>dispatch</code></p>
<p>下面，我们还是要优化一下模板中的调用。</p>
<p>这里通过<code>mapActions</code>函数来进行优化，该函数返回的是一个对象，对象中的方法封装了对<code>dispatch</code>的调用，该函数的参数可以接收数组也可以接收对象。</p>
<p>我们这里只演示数组的形式。<code>mapActions</code>与<code>mapMutations</code>一样，都是映射的方法。所以定义在<code>methods</code>中。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; mapGetters, mapState, mapMutations, mapActions &#125; <span class="keyword">from</span> <span class="string">&quot;vuex&quot;</span>;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">  <span class="attr">computed</span>: &#123;</span><br><span class="line">    <span class="comment">//mapState会返回一个对象，包含了两个计算属性对应的方法，</span></span><br><span class="line">    <span class="comment">//当前的计算属性为count和msg</span></span><br><span class="line">    <span class="comment">//所以对应的方法形式为: count:state=&gt;state.count</span></span><br><span class="line">    <span class="comment">// ...mapState([&quot;count&quot;, &quot;msg&quot;]),</span></span><br><span class="line">    ...<span class="title function_">mapState</span>(&#123; <span class="attr">num</span>: <span class="string">&quot;count&quot;</span>, <span class="attr">message</span>: <span class="string">&quot;msg&quot;</span> &#125;),</span><br><span class="line">    ...<span class="title function_">mapGetters</span>([<span class="string">&quot;reverseMsg&quot;</span>]),</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">methods</span>: &#123;</span><br><span class="line">    ...<span class="title function_">mapMutations</span>([<span class="string">&quot;increate&quot;</span>]),</span><br><span class="line"></span><br><span class="line">    ...<span class="title function_">mapActions</span>([<span class="string">&quot;increateAsync&quot;</span>]),</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>模板中的修改：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&lt;h2&gt;Action&lt;/h2&gt;</span><br><span class="line">&lt;!-- &lt;button @click=&quot;$store.dispatch(&#x27;increateAsync&#x27;, 5)&quot;&gt;Action&lt;/button&gt; --&gt;</span><br><span class="line">&lt;button @click=&quot;increateAsync(6)&quot;&gt;Action&lt;/button&gt;</span><br></pre></td></tr></table></figure>

<p>以上是<code>Action</code>的基本使用，当需要执行异步操作的时候，需要用到<code>Action</code>,<code>Action</code>内部修改状态必须通过提交<code>Mutation</code>来完成。</p>
<h1 id="11、Module"><a href="#11、Module" class="headerlink" title="11、Module"></a>11、Module</h1><p>这节课我们来看一下<code>Module</code>模块的内容。</p>
<p>如果我们把所有的状态都存储到了<code>State</code>中，后期会变得非常难维护，<code>Store</code>也就变得非常臃肿，为了解决这个问题，<code>Vuex</code>允许我们将<code>Store</code>分隔成模块。每一个模块都有自己的<code>State</code>,<code>Mutation</code>,<code>Action</code>,<code>Getter</code>等。当状态内容非常多的时候，<code>Module</code>是非常有用的。</p>
<p>下面我们先来定义模块的内容，当模块定义好以后，还需要在<code>Store</code>中进行注册。</p>
<p>在<code>src/store</code>目录下面，创建<code>modules</code>目录，该目录下面存储的就是模块的内容，这里我们有两个模块，分别是商品与购物车。</p>
<p>具体内容如下:<code>products.js</code>定义的是商品模块。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> state = &#123;</span><br><span class="line">  <span class="attr">products</span>: [</span><br><span class="line">    &#123; <span class="attr">id</span>: <span class="number">1</span>, <span class="attr">title</span>: <span class="string">&quot;iPhone11&quot;</span>, <span class="attr">price</span>: <span class="number">8000</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">id</span>: <span class="number">2</span>, <span class="attr">title</span>: <span class="string">&quot;iPhone12&quot;</span>, <span class="attr">price</span>: <span class="number">10000</span> &#125;,</span><br><span class="line">  ],</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">const</span> getters = &#123;&#125;;</span><br><span class="line"><span class="keyword">const</span> mutations = &#123;</span><br><span class="line">  <span class="comment">//修改商品数据</span></span><br><span class="line">  <span class="title function_">setProducts</span>(<span class="params">state, payload</span>) &#123;</span><br><span class="line">    state.<span class="property">products</span> = payload;</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">const</span> actions = &#123;&#125;;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">  state,</span><br><span class="line">  getters,</span><br><span class="line">  mutations,</span><br><span class="line">  actions,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p><code>cart.js</code>文件中定义的是购物车的模块，这里只是定义了基本的结构。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> state = &#123;&#125;;</span><br><span class="line"><span class="keyword">const</span> getters = &#123;&#125;;</span><br><span class="line"><span class="keyword">const</span> mutations = &#123;&#125;;</span><br><span class="line"><span class="keyword">const</span> actions = &#123;&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">  state,</span><br><span class="line">  getters,</span><br><span class="line">  mutations,</span><br><span class="line">  actions,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>下面返回到<code>store/index.js</code>文件中，在<code>Store</code>中完成如上两个模块的注册。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="title class_">Vue</span> <span class="keyword">from</span> <span class="string">&quot;vue&quot;</span>;</span><br><span class="line"><span class="keyword">import</span> <span class="title class_">Vuex</span> <span class="keyword">from</span> <span class="string">&quot;vuex&quot;</span>;</span><br><span class="line"><span class="keyword">import</span> products <span class="keyword">from</span> <span class="string">&quot;./modules/products&quot;</span>;</span><br><span class="line"><span class="keyword">import</span> cart <span class="keyword">from</span> <span class="string">&quot;./modules/cart&quot;</span>;</span><br><span class="line"><span class="title class_">Vue</span>.<span class="title function_">use</span>(<span class="title class_">Vuex</span>);</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="keyword">new</span> <span class="title class_">Vuex</span>.<span class="title class_">Store</span>(&#123;</span><br><span class="line">  <span class="attr">state</span>: &#123;</span><br><span class="line">    <span class="attr">count</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">msg</span>: <span class="string">&quot;Hello Vuex&quot;</span>,</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="attr">getters</span>: &#123;</span><br><span class="line">    <span class="title function_">reverseMsg</span>(<span class="params">state</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> state.<span class="property">msg</span>.<span class="title function_">split</span>(<span class="string">&quot;&quot;</span>).<span class="title function_">reverse</span>().<span class="title function_">join</span>(<span class="string">&quot;&quot;</span>);</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">mutations</span>: &#123;</span><br><span class="line">    <span class="comment">//payload是调用mutations的时候传递的额外的值。</span></span><br><span class="line">    <span class="comment">//这里就是传递过来的要累加的值</span></span><br><span class="line">    <span class="title function_">increate</span>(<span class="params">state, payload</span>) &#123;</span><br><span class="line">      state.<span class="property">count</span> += payload;</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">actions</span>: &#123;</span><br><span class="line">    <span class="comment">//context:上下文，该对象中包含了state,commit,getters等成员</span></span><br><span class="line">    <span class="title function_">increateAsync</span>(<span class="params">context, payload</span>) &#123;</span><br><span class="line">      <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        context.<span class="title function_">commit</span>(<span class="string">&quot;increate&quot;</span>, payload);</span><br><span class="line">      &#125;, <span class="number">2000</span>);</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">//完成模块的注册</span></span><br><span class="line">  <span class="attr">modules</span>: &#123;</span><br><span class="line">    products,</span><br><span class="line">    cart,</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>在上面的代码中，我们首先导入了两个模块，然后在<code>modules</code>中注册了两个模块。</p>
<p>下面，我们来看一下在视图中怎样使用模块？</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&lt;h2&gt;</span><br><span class="line">      Module</span><br><span class="line">    &lt;/h2&gt;</span><br><span class="line">products:&#123;&#123; $store.state.products.products &#125;&#125;</span><br><span class="line">&lt;br /&gt;</span><br><span class="line">&lt;button @click=&quot;$store.commit(&#x27;setProducts&#x27;, [])&quot;&gt;Mutation&lt;/button&gt;</span><br></pre></td></tr></table></figure>

<p>通过上面的代码，我们可以看到要想获取模块中的<code>state</code>,需要通过<code>$store.state.products.products</code>,第一个<code>products</code>是模块的名字，第二个<code>products</code>是模块中的<code>state</code>.关于<code>Mutation</code>的使用与以前是一样的，这里将<code>products</code>设置为了空数组。</p>
<p>下面，我们还是对模板中的内容进行优化，在优化之前，建议给模块添加命名空间，这样在模块中的代码结构会变得非常的清晰。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> state = &#123;</span><br><span class="line">  <span class="attr">products</span>: [</span><br><span class="line">    &#123; <span class="attr">id</span>: <span class="number">1</span>, <span class="attr">title</span>: <span class="string">&quot;iPhone11&quot;</span>, <span class="attr">price</span>: <span class="number">8000</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">id</span>: <span class="number">2</span>, <span class="attr">title</span>: <span class="string">&quot;iPhone12&quot;</span>, <span class="attr">price</span>: <span class="number">10000</span> &#125;,</span><br><span class="line">  ],</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">const</span> getters = &#123;&#125;;</span><br><span class="line"><span class="keyword">const</span> mutations = &#123;</span><br><span class="line">  <span class="title function_">setProducts</span>(<span class="params">state, payload</span>) &#123;</span><br><span class="line">    state.<span class="property">products</span> = payload;</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">const</span> actions = &#123;&#125;;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">  <span class="comment">//开启命名空间</span></span><br><span class="line">  <span class="attr">namespaced</span>: <span class="literal">true</span>,</span><br><span class="line">  state,</span><br><span class="line">  getters,</span><br><span class="line">  mutations,</span><br><span class="line">  actions,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>在<code>products.js</code>文件中导出模块的时候开启了命名空间。</p>
<p>同理，在<code>cart.js</code>文件中也要开启命名空间。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> state = &#123;&#125;;</span><br><span class="line"><span class="keyword">const</span> getters = &#123;&#125;;</span><br><span class="line"><span class="keyword">const</span> mutations = &#123;&#125;;</span><br><span class="line"><span class="keyword">const</span> actions = &#123;&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">  <span class="comment">//开启命名空间</span></span><br><span class="line">  <span class="attr">namespaced</span>: <span class="literal">true</span>,</span><br><span class="line">  state,</span><br><span class="line">  getters,</span><br><span class="line">  mutations,</span><br><span class="line">  actions,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>下面开始对模板中的内容进行修改。</p>
<p>对应模板的修改如下：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&lt;h2&gt;</span><br><span class="line">      Module</span><br><span class="line">    &lt;/h2&gt;</span><br><span class="line">&lt;!-- products:&#123;&#123; $store.state.products.products &#125;&#125;&lt;br /&gt;</span><br><span class="line">    &lt;button @click=&quot;$store.commit(&#x27;setProducts&#x27;, [])&quot;&gt;Mutation&lt;/button&gt; --&gt;</span><br><span class="line">products:&#123;&#123; products &#125;&#125;</span><br><span class="line">&lt;br /&gt;</span><br><span class="line">&lt;button @click=&quot;setProducts([])&quot;&gt;Mutation&lt;/button&gt;</span><br></pre></td></tr></table></figure>

<p>通过上面的改造，我们可以很容易看到，<code>state</code>与<code>mutation</code>是从哪个模块中获取到的，不带命名空间就是在全局的<code>Store</code>中获取的。</p>
<h1 id="12、Vuex-严格模式"><a href="#12、Vuex-严格模式" class="headerlink" title="12、Vuex 严格模式"></a>12、Vuex 严格模式</h1><p>在前面的课程中，我们讲解过所有的状态的更新必须通过提交<code>Mutation</code>来完成，但是这仅仅是一个约定，其实我们可以再组件中直接通过<code>$store.state.msg</code>这种方式来直接修改<code>msg</code>这个状态的值。从语法的层面上来讲，这是没有问题的。但是，这样却破坏了<code>Vuex</code>的约定。开启了<code>Vuex</code>的严格模式后，如果在组件中直接修改<code>state</code>，会出现错误。</p>
<p>在<code>store/index.js</code>文件中，创建<code>Store</code>的实例的时候，开启严格模式：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="keyword">new</span> <span class="title class_">Vuex</span>.<span class="title class_">Store</span>(&#123;</span><br><span class="line">  <span class="attr">strict</span>: <span class="literal">true</span>,<span class="comment">//开启严格模式</span></span><br><span class="line">  <span class="attr">state</span>: &#123;</span><br><span class="line">    <span class="attr">count</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">msg</span>: <span class="string">&quot;Hello Vuex&quot;</span>,</span><br><span class="line">  &#125;,</span><br></pre></td></tr></table></figure>

<p>在<code>App.vue</code>文件中，尝试修改<code>state</code>中的数据。</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&lt;h2&gt;严格模式&lt;/h2&gt;</span><br><span class="line">&lt;button @click=&quot;$store.state.msg = &#x27;abc&#x27;&quot;&gt;strict&lt;/button&gt;</span><br></pre></td></tr></table></figure>

<p>在浏览器中，当我们单击以上按钮的时候，在控制台中会出现错误，当然，视图中的内容也发生了改变。</p>
<p>注意：不能在生产环境中开启严格模式，因为严格模式会不断的检查是否出现直接修改状态的情况，这样会影响性能。我们可以在开发环境中开启严格模式，在生产环境中关闭严格模式。</p>
<p>所以，这里可以将<code>strict</code>的值，修改成如下的形式：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="keyword">new</span> <span class="title class_">Vuex</span>.<span class="title class_">Store</span>(&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//当npm run build的时候，NODE_ENV的值为production，生产环境</span></span><br><span class="line">  <span class="attr">strict</span>: process.<span class="property">env</span>.<span class="property">NODE_ENV</span> !== <span class="string">&quot;production&quot;</span>,</span><br><span class="line">  <span class="attr">state</span>: &#123;</span><br><span class="line">    <span class="attr">count</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">msg</span>: <span class="string">&quot;Hello Vuex&quot;</span>,</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br></pre></td></tr></table></figure>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://example.com">Justic</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://example.com/2022/07/15/Vue/Vuex%20%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86/Vuex%20%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86/">http://example.com/2022/07/15/Vue/Vuex 状态管理/Vuex 状态管理/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://justicc.top/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://example.com" target="_blank">Justic</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Vue/">Vue</a></div><div class="post_share"><div class="social-share" data-image="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/m9/wallhaven-m9y289.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/img/wechat.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="/img/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/img/alipay.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="/img/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2022/07/15/Vue/Vue%20%E5%B8%B8%E8%A7%81%E9%9D%A2%E8%AF%95%E9%A2%98/Vue%E9%9D%A2%E8%AF%95%E9%A2%98/"><img class="prev-cover" src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/yj/wallhaven-yj1kgl.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Vue 面试题</div></div></a></div><div class="next-post pull-right"><a href="/2022/07/13/JavaScript/JavaScript%20%E9%9D%A2%E8%AF%95%E7%B2%BE%E8%AE%B2/JavaScript%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/"><img class="next-cover" src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/3z/wallhaven-3zgz2y.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">JavaScript 性能优化</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2022/07/13/Vue/Vue%20Router/vueRouter/" title="Vue 路由"><img class="cover" src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/ne/wallhaven-ne8mzl.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-13</div><div class="title">Vue 路由</div></div></a></div><div><a href="/2022/07/13/Vue/Vue%20%E5%93%8D%E5%BA%94%E5%BC%8F%E5%8E%9F%E7%90%86/Vue%E5%93%8D%E5%BA%94%E5%BC%8F%E5%8E%9F%E7%90%86/" title="Vue 响应式原理"><img class="cover" src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/j3/wallhaven-j3qq15.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-13</div><div class="title">Vue 响应式原理</div></div></a></div><div><a href="/2022/10/20/Vue/Vue%20%E5%93%8D%E5%BA%94%E5%BC%8F%E8%A7%A3%E6%9E%90/Vue%E5%93%8D%E5%BA%94%E5%BC%8F%E8%A7%A3%E6%9E%90/" title="Vue 响应式解析"><img class="cover" src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/z8/wallhaven-z82evv.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-10-20</div><div class="title">Vue 响应式解析</div></div></a></div><div><a href="/2022/07/15/Vue/Vue%20%E6%9C%8D%E5%8A%A1%E5%99%A8%E6%B8%B2%E6%9F%93/Vue%E6%9C%8D%E5%8A%A1%E7%AB%AF%E6%B8%B2%E6%9F%93/" title="Vue 服务器渲染"><img class="cover" src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/ne/wallhaven-ne8mzl.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-15</div><div class="title">Vue 服务器渲染</div></div></a></div><div><a href="/2022/07/15/Vue/Vue%20%E6%BA%90%E7%A0%81%E8%A7%A3%E8%AF%BB/Vue%E6%BA%90%E7%A0%81%E8%A7%A3%E8%AF%BB/" title="Vue 源码解读"><img class="cover" src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/j3/wallhaven-j3qq15.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-15</div><div class="title">Vue 源码解读</div></div></a></div><div><a href="/2022/07/15/Vue/Vue%20%E8%99%9A%E6%8B%9Fdom/Vue%20%E8%99%9A%E6%8B%9Fdom/" title="Vue 虚拟DOM"><img class="cover" src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/k7/wallhaven-k7jmg6.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-15</div><div class="title">Vue 虚拟DOM</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="https://portrait.gitee.com/uploads/avatars/user/2982/8948190_JIAXInT_1624177607.png!avatar200" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Justic</div><div class="author-info__description">最是人间留不住 朱颜辞镜花辞树</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">22</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">2</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">3</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Vuex-%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86"><span class="toc-text">Vuex 状态管理</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#1%E3%80%81%E4%B8%BB%E8%A6%81%E5%86%85%E5%AE%B9"><span class="toc-text">1、主要内容</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#2%E3%80%81%E7%BB%84%E4%BB%B6%E5%86%85%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86%E6%B5%81%E7%A8%8B"><span class="toc-text">2、组件内状态管理流程</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#3%E3%80%81%E7%AE%80%E6%98%93%E7%9A%84%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86%E6%96%B9%E6%A1%88"><span class="toc-text">3、简易的状态管理方案</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#4%E3%80%81%E4%BB%80%E4%B9%88%E6%98%AF-Vuex"><span class="toc-text">4、什么是 Vuex</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#5%E3%80%81Vuex-%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5"><span class="toc-text">5、Vuex 核心概念</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#6%E3%80%81Vuex-%E5%9F%BA%E6%9C%AC%E7%BB%93%E6%9E%84"><span class="toc-text">6、Vuex 基本结构</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#7%E3%80%81State"><span class="toc-text">7、State</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#8%E3%80%81Getter"><span class="toc-text">8、Getter</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#9%E3%80%81Mutation"><span class="toc-text">9、Mutation</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#10%E3%80%81Action"><span class="toc-text">10、Action</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#11%E3%80%81Module"><span class="toc-text">11、Module</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#12%E3%80%81Vuex-%E4%B8%A5%E6%A0%BC%E6%A8%A1%E5%BC%8F"><span class="toc-text">12、Vuex 严格模式</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2022/11/09/JavaScript/ES6%E6%96%B0%E7%89%B9%E6%80%A7/index/" title="ES6新特性"><img src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/m9/wallhaven-m9y289.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="ES6新特性"/></a><div class="content"><a class="title" href="/2022/11/09/JavaScript/ES6%E6%96%B0%E7%89%B9%E6%80%A7/index/" title="ES6新特性">ES6新特性</a><time datetime="2022-11-09T12:55:33.000Z" title="发表于 2022-11-09 20:55:33">2022-11-09</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/10/20/Vue/Vue%20%E5%93%8D%E5%BA%94%E5%BC%8F%E8%A7%A3%E6%9E%90/Vue%E5%93%8D%E5%BA%94%E5%BC%8F%E8%A7%A3%E6%9E%90/" title="Vue 响应式解析"><img src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/z8/wallhaven-z82evv.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Vue 响应式解析"/></a><div class="content"><a class="title" href="/2022/10/20/Vue/Vue%20%E5%93%8D%E5%BA%94%E5%BC%8F%E8%A7%A3%E6%9E%90/Vue%E5%93%8D%E5%BA%94%E5%BC%8F%E8%A7%A3%E6%9E%90/" title="Vue 响应式解析">Vue 响应式解析</a><time datetime="2022-10-20T12:05:37.000Z" title="发表于 2022-10-20 20:05:37">2022-10-20</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/08/08/JavaScript/JavaScript%E5%8E%9F%E5%9E%8B%E5%92%8C%E5%8E%9F%E5%9E%8B%E9%93%BE/index/" title="JavaScript原型和原型链"><img src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/z8/wallhaven-z82evv.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JavaScript原型和原型链"/></a><div class="content"><a class="title" href="/2022/08/08/JavaScript/JavaScript%E5%8E%9F%E5%9E%8B%E5%92%8C%E5%8E%9F%E5%9E%8B%E9%93%BE/index/" title="JavaScript原型和原型链">JavaScript原型和原型链</a><time datetime="2022-08-08T09:08:31.000Z" title="发表于 2022-08-08 17:08:31">2022-08-08</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/08/08/JavaScript/JavaScript%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%A2%9E%E5%BC%BA%E7%9F%A5%E8%AF%86/index/" title="JavaScript对象的增强知识"><img src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/j3/wallhaven-j3qq15.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JavaScript对象的增强知识"/></a><div class="content"><a class="title" href="/2022/08/08/JavaScript/JavaScript%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%A2%9E%E5%BC%BA%E7%9F%A5%E8%AF%86/index/" title="JavaScript对象的增强知识">JavaScript对象的增强知识</a><time datetime="2022-08-08T07:43:36.000Z" title="发表于 2022-08-08 15:43:36">2022-08-08</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/08/08/JavaScript/JavaScript%E5%87%BD%E6%95%B0%E5%A2%9E%E5%BC%BA%E7%9F%A5%E8%AF%86/index/" title="JavaScript函数增强知识"><img src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/28/wallhaven-2881yx.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JavaScript函数增强知识"/></a><div class="content"><a class="title" href="/2022/08/08/JavaScript/JavaScript%E5%87%BD%E6%95%B0%E5%A2%9E%E5%BC%BA%E7%9F%A5%E8%AF%86/index/" title="JavaScript函数增强知识">JavaScript函数增强知识</a><time datetime="2022-08-08T03:25:40.000Z" title="发表于 2022-08-08 11:25:40">2022-08-08</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/m9/wallhaven-m9y289.png')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By Justic</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a><img src= "" data-lazy-src="https://static.dy208.cn/o_1dfilp8ruo521thr1hvf18ji17soa.png">
<a href="http://www.beian.miit.gov.cn/"  style="color:#f72b07" target="_blank">晋ICP备2021014440号-2</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="聊天"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: 'KgIigedIwh0GobYsWWfPMEdO-gzGzoHsz',
      appKey: 'WpJEQP22asTau19i2tq1yQhU',
      avatar: 'justic',
      serverURLs: '',
      emojiMaps: "",
      path: window.location.pathname,
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !false) {
  if (false) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script></div><div class="aplayer no-destroy" data-id="5076309057" data-server="netease" data-type="playlist" data-fixed="true" data-autoplay="true" data-lrcType="-1"> </div><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-nest.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = true;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-show-text" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-show-text.min.js" data-mobile="true" data-text="富强,民主,文明,和谐,平等,公正,法治,爱国,敬业,诚信,友善" data-fontsize="15px" data-random="true" async="async"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/metingjs/dist/Meting.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><!-- hexo injector body_end start --><script data-pjax>
  function butterfly_clock_anzhiyu_injector_config(){
    var parent_div_git = document.getElementsByClassName('sticky_layout')[0];
    var item_html = '<div class="card-widget card-clock"><div class="card-glass"><div class="card-background"><div class="card-content"><div id="hexo_electric_clock"><img class="entered loading" id="card-clock-loading" src= "" data-lazy-src="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/loading.gif" style="height: 120px; width: 100%;" data-ll-status="loading"/></div></div></div></div></div>';
    console.log('已挂载butterfly_clock_anzhiyu')
    parent_div_git.insertAdjacentHTML("afterbegin",item_html)
    }
  var elist = 'null'.split(',');
  var cpage = location.pathname;
  var epage = 'all';
  var qweather_key = 'f854dfdd82d747fca7fd04f092861e87';
  var gaud_map_key = '427416c518f4476a01117be40057a892';
  var baidu_ak_key = 'undefined';
  var flag = 0;
  var clock_rectangle = '112.982279,28.19409';
  var clock_default_rectangle_enable = 'false';

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_clock_anzhiyu_injector_config();
  }
  else if (epage === cpage){
    butterfly_clock_anzhiyu_injector_config();
  }
  </script><script src="https://widget.qweather.net/simple/static/js/he-simple-common.js?v=2.0"></script><script data-pjax src="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/clock.min.js"></script><!-- hexo injector body_end end --></body></html>